package cn.nit.algorithm.experiment;

/**
 *
 * 试验一：逆置单链表
 *
 *   对于不带头结点的单链表L,设计一个递归算法逆置所有节点。编写完整的实验程序，
 *   并采用相应数据进行测试。
 *
 */

public class Experiment2 {
    Link link;
    int linkLength = 1;
    Link preLink=null;
    Link nextLink = null;
    public String totalString = "";

    public Experiment2() {
        link = new Link();
        link.data = 1;
        Link tempLink = link;
        for (int i = 0; i < 10; i++) {
            Link inLink = new Link();
            inLink.data = i + 2;
            tempLink.next = inLink;
            tempLink = inLink;
            linkLength++;
        }
    }

    public Link reverseLink(Link link){
        if(link.next==null){
            link.next = preLink;
            return link;
        }
        nextLink = link.next;
        link.next = preLink;
        preLink = link;
        return reverseLink(nextLink);
    }

//    public static void main(String[] args) {
//        Experiment2 experiment = new Experiment2();
//        System.out.println(new Link().print(experiment.link));
//        System.out.println(experiment.linkLength);
//        System.out.println(new Link().print(experiment.reverseLink(experiment.link)));
//    }

    public String runMain(){
        totalString+=new Link().print(link)+"<br>";
        totalString+="长度为："+linkLength+"<br>";
        totalString+=new Link().print(reverseLink(link))+"<br>";
        return totalString;
    }


}

class Link {
    Link next = null;
    int data = 0;

    public String print(Link link) {
        Link temp = link;
        String out = "单链表： ";
        while (temp != null) {
            out = out + String.valueOf(temp.data) + "  ";
            temp = temp.next;
        }
        return out;
    }
}
